<template>
  <t-adaptive-page
    v-loading="state.loading"
    class="menu_mange"
    tableTitle="预收款开票列表"
    row-key="path"
    isCopy
    ref="tAdaptivePageRef"
    isExpansion
    :isTTableSelfFilling="false"
    :isShowPagination="false"
    columnSetting
    :table="state.table"
    :columns="state.table.columns"
    isShowWidthSize
    :opts="opts"
    :widthSize="4"
    @submit="conditionEnter"
    @radio-change="selecUpdateChange"
  >
    <template #CreateDate="{ scope }">
      <div>{{ parseTime(scope.row.createDate) }}</div>
    </template>
    <template #Ddate="{ scope }">
      <div>{{ parseTime(scope.row.Ddate,'{y}-{m}-{d}') }}</div>
    </template>

    <template #CCode="{ scope }">
      <el-link type="primary" @click="handlView(scope.row)">{{ scope.row.CCode }}</el-link>
    </template>

    <template #State="{scope}">
      <el-tag type="info" v-if="scope.row.State=='0'">开立</el-tag>
      <el-tag type="success" v-if="scope.row.State=='2'">已审核</el-tag>
      <el-tag type="primary" v-if="scope.row.State=='1'">送审中</el-tag>
      <el-tag type="danger" v-if="scope.row.State=='3'">已关闭</el-tag>
    </template>

    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button type="primary" @click="handlEedit(state.selectedRow)"  v-if="['0'].includes(state.selectedRow.State) && checkPermission('修改', state.roleList)">编辑</el-button>
        <el-button type="primary"  @click="deleteHandles(state.selectedRow)" v-if="['0'].includes(state.selectedRow.State) && checkPermission('删除', state.roleList)">删除</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow,'2')" v-if="['0'].includes(state.selectedRow.State) && checkPermission('审核', state.roleList)">审核</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow, '0')" v-if="['2'].includes(state.selectedRow.State) && checkPermission('弃审', state.roleList)">弃审</el-button>
        <el-button   @click="handlCheck(state.selectedRow,'3')" type="primary"  v-if="state.selectedRow.State!=='3' && checkPermission('关闭', state.roleList)" >关闭</el-button>
      </div>
    </template>




    <template #footerBtn>
      <el-button type="danger"  @click="addHandle()">新增</el-button>
<!--      <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length" v-if="checkPermission('删除', state.roleList)">删除</el-button>-->

      <el-button type="primary" @click="tAdaptivePageRef.TQueryConditionPage.checkHandle()"
        >查询</el-button
      >
      <el-button type="danger" @click="tAdaptivePageRef.TQueryConditionPage.resetHandle()"
        >重置</el-button
      >
    </template>


  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog
      :title="state.title"
      top="10px"
      width="70%"
      v-model="state.dialogSelectEnt"
      draggable
      :close-on-click-modal="false"
      @close="closeDialog"
  >
    <el-form ref="formRef" :disabled="!state.isEdit" :model="state.formData" :rules="state.rules" label-position="right">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="工作号" prop="JobNum">
            <JobNumberDropdown
                  :isUseGlobalData="false"
                  v-model="state.formData.JobNum"
                  @change="updateContarctInfo"
                  :contract-list="contractList"
              />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同号" prop="ContractNum">
             <el-input v-model="state.formData.ContractNum" disabled placeholder="请输入合同号" clearable />
          
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="ProjectName">
            <el-input v-model="state.formData.ProjectName" disabled placeholder="请输入项目名称" clearable />
          </el-form-item>
        </el-col>
        
      </el-row>

      <el-row :gutter="10">
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="发票号" prop="CCode">-->
        <!--              <el-input-->
        <!--                v-model="state.formData.CCode"-->
        <!--                disabled-->
        <!--                placeholder="请输入发票号"-->
        <!--                clearable-->
        <!--              />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <el-col :span="12">
          <el-form-item label="客户名称" prop="CustName">
            <el-input v-model="state.formData.CustName" disabled placeholder="请输入客户名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务员" prop="Salesman">
            <el-select
                @change="changeSalesman"
                v-model="state.formData.Salesman"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择业务员"
                remote-show-suffix
            >
              <el-option
                  :label="item.cPsn_Name"
                  :value="item.cPsn_Num"
                  v-for="(item, index) in state.userList"
                  :key="index"
              >
                <span style="float: left">{{ item.cPsn_Name }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                >【{{ item.cDepName }}】</span
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售部门" prop="DeptName">
            <el-input  v-model="state.formData.DeptName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="PaymentTerms">
            <el-input
                v-model="state.formData.PaymentTerms"
                placeholder="请输入联系电话"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="客户地址" prop="CustAdd">
            <el-input
                disabled
                v-model="state.formData.CustAdd"
                placeholder="请输入客户地址"
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行" prop="BankCode">
            <el-input
                v-model="state.formData.BankCode"
                placeholder="请输入开户银行"
                disabled
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="BankAccount">
            <el-input v-model="state.formData.BankAccount" disabled placeholder="请输入账号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税号" prop="Tax">
            <el-input v-model="state.formData.Tax" disabled placeholder="请输入税号" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="税率" prop="Rate">
            <el-input-number
                v-model="state.formData.Rate"
                placeholder="请输入税率"
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票日期" prop="Ddate">
            <t-date-picker
                v-model="state.formData.Ddate"
                placeholder="请输入开票日期"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <t-layout-page-item>
      <t-table
          title="明细"
          ref="singleEdit"
          show-summary
          :table="state.clumTable"
          :columns="state.clumTable.columns"
          :isShowPagination="false"
          :listTypeInfo="state.clumTable.listTypeInfo"
      >
        <template #toolbar>
          <t-select-table
              v-if="state.isEdit"
              ref="selectTableFP"
              :table="state.editTable"
              :columns="state.editTable.columns"
              :max-height="400"
              multiple
              :defaultSelectVal="state.defaultSelectVal"
              @selectionChange="selectionChange"
              :keywords="{ label: 'CinvName', value: 'Id' }"
          ></t-select-table>
          <el-button style="margin-left: 15px" type="primary" @click="addToTable" v-if="state.isEdit">确认选择</el-button>
        </template>
      </t-table>
    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" v-if="state.isEdit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  修改-->
  <el-dialog
      :title="state.detail.title"
      top="10px"
      width="90%"
      v-model="state.detail.dialogSelectEnt"
      draggable
      :close-on-click-modal="false"
      @close="closeDialog"
  >
    <el-form ref="formRef" disabled :model="state.detail.formData" :rules="state.rules" label-position="right">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="合同号" prop="ContractNum">
            <el-input v-model="state.detail.formData.ContractNum" disabled placeholder="请输入合同号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="ProjectName">
            <el-input v-model="state.detail.formData.ProjectName" disabled placeholder="请输入项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作号" prop="JobNum">
            <el-input v-model="state.detail.formData.JobNum" disabled placeholder="请输入工作号" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="CustName">
            <el-input v-model="state.detail.formData.CustName" disabled placeholder="请输入客户名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务员" prop="Salesman">
            <el-select
                @change="changeSalesman"
                v-model="state.detail.formData.Salesman"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请选择业务员"
                remote-show-suffix
            >
              <el-option
                  :label="item.cPsn_Name"
                  :value="item.cPsn_Num"
                  v-for="(item, index) in state.userList"
                  :key="index"
              >
                <span style="float: left">{{ item.cPsn_Name }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
                >【{{ item.cDepName }}】</span
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售部门" prop="DeptName">
            <el-input  v-model="state.detail.formData.DeptName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="PaymentTerms">
            <el-input
                v-model="state.detail.formData.PaymentTerms"
                placeholder="请输入联系电话"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="客户地址" prop="CustAdd">
            <el-input
                disabled
                v-model="state.detail.formData.CustAdd"
                placeholder="请输入客户地址"
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行" prop="BankCode">
            <el-input
                v-model="state.detail.formData.BankCode"
                placeholder="请输入开户银行"
                disabled
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="BankAccount">
            <el-input v-model="state.detail.formData.BankAccount" disabled placeholder="请输入账号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税号" prop="Tax">
            <el-input v-model="state.detail.formData.Tax" disabled placeholder="请输入税号" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="税率" prop="Rate">
            <el-input-number
                v-model="state.detail.formData.Rate"
                placeholder="请输入税率"
                clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票日期" prop="Ddate">
            <t-date-picker
                v-model="state.detail.formData.Ddate"
                placeholder="请输入开票日期"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <t-layout-page-item>

      <el-table :data="state.detail.gridData">
        <el-table-column prop="LineNum" label="序号" width="80"></el-table-column>
        <el-table-column prop="CinvCode" label="产品编码" width="100"></el-table-column>
        <el-table-column prop="CinvName" label="产品名称" width="160"></el-table-column>
        <el-table-column prop="CinvAdd" label="产品型号" width="110"></el-table-column>
        <el-table-column prop="Qty" label="数量" width="100"></el-table-column>
        <el-table-column prop="CustCinvName" label="客户产品名称" width="160"></el-table-column>
        <el-table-column prop="CustCinvAdd" label="客户产品规格" width="120"></el-table-column>
        <el-table-column prop="Unit" label="单位" width="100"></el-table-column>
        <el-table-column prop="UnPrice" label="不含税单价" width="100"></el-table-column>
        <el-table-column prop="UnAmount" label="不含税金额" width="100"></el-table-column>
        <el-table-column prop="Rate" label="税率" width="100"></el-table-column>
        <el-table-column prop="Price" label="含税单价" width="100"></el-table-column>
        <el-table-column prop="Amount" label="含税金额" width="100"></el-table-column>
        <el-table-column prop="Remark" label="备注" width="100"></el-table-column>
      </el-table>
    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx">
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { DelJHYS, GetOnefhYS, SaveFHYS, selcetDataList } from '@/api/advance_panment_invoicing'
import { getContractInfo, uploadFile,findbaseBasicManage,GetSalesMan,ApproveDocument,userRole } from '@/api/base'
import { parseTime,checkPermission } from '@/utils/util'
import { cubasdocStore } from '@/stores/modules/cubasdoc'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import JobNumberDropdown from "@/components/JobNumberDropdown/index.vue";

const tAdaptivePageRef: any = ref(null)
const selectTable = ref()
const contractList = ref([])


const cubasdoc = cubasdocStore()

/* pc端文件上传时候------------------------------------- */
// 上传文件前


const handlView = async (row: any) => {
  let { Data } = await GetOnefhYS({ id: row.Id })
  state.detail.formData = Data.Main
  state.detail.gridData = Data.SubList.map((item: any) => {
    return {
      ...item,
      Qty: item.Quantity
    }
  })
  state.detail.title = '详情'
  state.detail.dialogSelectEnt = true
}



const handlEedit = async (row: any) => {
  let { Data } = await GetOnefhYS({ id: row.Id })
  state.formData = Data.Main
  state.clumTable.data = Data.SubList.map((item: any) => {
    return {
      ...item,
      Qty: item.Quantity
    }
  })
  //过滤合同
  let contractInfo = cubasdoc.contractList.find((item: any) => item.ContractNum == row.ContractNum)
  if (contractInfo) {
    await findContractInfo(contractInfo.Id)
    state.defaultSelectVal = Data.SubList.map((item: any) => item.ConSubId)
    state.dialogSelectEnt = true
    state.isEdit = true
    state.title='修改预开票收款'
  }
}

const handleDelete = (row: any) => {

  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}

//表格配置
const state: any = reactive({
  roleList:[],
  isEdit:false,
  queryData: {
    JobNum: null, // 工作号
    ContractNum: null, // 合同号
    CCode: null,
    CreateFrom: null, //制单开始时间
    CreateTo: null, //制单结束时间
    CreateBy: null //建档人
  },
  table: {
    border: true,
    // 接口返回数据
    data: [],
    firstColumn: { type: 'radio', fixed: true },
    // 表头数据
    columns: [
      { prop: 'CCode', label: '单据编号', minWidth: 130, slotName: 'CCode',fixed: 'left' },
      { prop: 'CustName', label: '客户名称', minWidth: 180,fixed: 'left' },
      { prop: 'ContractNum', label: '合同号', minWidth: 160 },
      { prop: 'Ddate', label: '单据日期', minWidth: 120, slotName: 'Ddate' },
      { prop: 'State', label: '状态', minWidth: 100, slotName: 'State' },
      { prop: 'BankCode', label: '开户银行  ', minWidth: 120 },
      { prop: 'BankAccount', label: '银行账号  ', minWidth: 120 },
      { prop: 'Rate', label: '税率', minWidth: 120 },
      { prop: 'SalesmanName', label: '业务员', minWidth: 120 },
      { prop: 'createDate', label: '创建时间', minWidth: 160,slotName:"CreateDate" },
    ],
  },
  loading: false,
  title: '预收款开票详情信息',
  dialogSelectEnt: false,
  formData: {},
  coseData: [],
  FileList: [],
  paymentTermsColumns: [
    { label: '编号', width: '100px', prop: 'Code', fixed: true },
    { label: '名称', width: '149px', prop: 'Name' }
  ],
  paymentTerms: [
    {
      Code: '0',
      Name: '预收款'
    },
    {
      Code: '1',
      Name: '投料款'
    },
    {
      Code: '2',
      Name: '厂验款'
    },
    {
      Code: '3',
      Name: '提货款'
    },
    {
      Code: '4',
      Name: '到货款'
    },
    {
      Code: '5',
      Name: '进度款1'
    },
    {
      Code: '6',
      Name: '进度款2'
    },
    {
      Code: '7',
      Name: '进度款3'
    },
    {
      Code: '8',
      Name: '验收款1'
    },
    {
      Code: '9',
      Name: '验收款2'
    },
    {
      Code: '10',
      Name: '决算款'
    },
    {
      Code: '11',
      Name: '质保金'
    }
  ],
  FileLists: [],

  clumTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "LineNum",
        label: "序号",

      },
      {
        prop: "CinvCode",
        label: "产品编码",
        width:150,

      },
      {
        prop: "CinvName",
        label: "产品名称",
        width:150,

      },
      {
        prop: "CinvAdd",
        label: "产品型号",
        width:150,
      },
      {
        prop: "Qty",
        label: "数量",
        width:150,
        canEdit: true,
        configEdit: {
          label: "数量",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },

      {
        prop: "CustCinvName",
        label: "客户产品名称",
        width:150,

      },
      {
        prop: "CustCinvAdd",
        label: "客户产品规格",
        width:150,
      },

      {
        prop: "Unit",
        label: "单位",

      },
      {
        prop: "UnPrice",
        label: "不含税单价",
        width:150,
        canEdit: true,
        configEdit: {
          label: "不含税单价",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: "UnAmount",
        label: "不含税金额",
        width:150,
        canEdit: true,
        configEdit: {
          label: "不含税金额",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: "Rate",
        label: "税率",
        //canEdit: true,
        width:120,

      },
      {
        prop: "Price",
        label: "含税单价",
        width:150,
        canEdit: true,
        configEdit: {
          label: "含税单价",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: "Amount",
        label: "含税金额",
        width:150,
        canEdit: true,
        configEdit: {
          label: "含税金额",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: "Remark",
        label: "备注",
        width:200,
        canEdit: true,
        configEdit: {
          label: "备注",
          type: "input",
          editComponent: "el-input",

        }
      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: 'selection' },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: 'CinvCode',
        label: '设备编码'
      },
      {
        prop: 'CinvName',
        label: '设备名称'
      },
      {
        prop: 'CinvAdd',
        label: '规格型号'
      },
      {
        prop: 'Quantity',
        label: '数量'
      },
      {
        prop: 'Unit',
        label: '单位'
      }
    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: '上层',
          key: '1'
        },
        {
          label: '中层',
          key: '2'
        },
        {
          label: '下层',
          key: '3'
        }
      ]
    },
    operator: [
      {
        text: '删除',
        fun: handleDelete,

      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: 'right', // 固定列表右边（left则固定在左边）
      width: 200,
      label: '操作'
    }
  },

  rules: {
    ContractNum: [{ required: true, message: '请选择合同号', trigger: 'change' }],
    ProjectName: [{ required: true, message: '请输入项目名称', trigger: 'change' }],
    FUnit: [{ required: true, message: '请选择发货单位', trigger: 'change' }],
    SUnit: [{ required: true, message: '请选择收货单位', trigger: 'change' }],
    FBatch: [{ required: true, message: '请输入批次', trigger: 'blur' }],
    PartyB: [{ required: true, message: '请输入乙方现场负责人', trigger: 'blur' }],
    JobNum: [{ required: true, message: '请输入工作号', trigger: 'blur' }],
    YSConclusion: [{ required: true, message: '请输入验收结论', trigger: 'blur' }]
  },
  defaultSelectVal: [],
  ids: [],
  uploadValue: null,
  userList:[],
  selectedRow:null,
  detail:{}
})

//表单配置
const opts = ref({
  JobNum: {
    label: '工作号',
    comp: 'el-input'
  },
  CCode: {
    label: '预收发票号',
    comp: 'el-input'
  },

  ContractNum: {
    label: '合同号',
    comp: 'el-input'
  },
  CreateBy: {
    label: '制单人',
    comp: 'el-input'
  },

  CreateFrom: {
    label: '制单日期',
    comp: 't-date-picker',
    span: 2,
    bind: {
      type: 'daterange'
    }
  }
})

//选择项
const cusoptions = ref([])
// 最终参数获取
const getQueryData = computed(() => {
  const { JobNum, ContractNum, CreateFrom, CCode, CreateBy } = toRefs(state.queryData)
  return {
    JobNum: JobNum.value,
    ContractNum: ContractNum.value,
    CCode: CCode.value,
    CreateBy: CreateBy.value,
    CreateFrom: CreateFrom.value && CreateFrom.value[0] ? CreateFrom.value[0] : null,
    CreateTo: CreateFrom.value && CreateFrom.value[1] ? CreateFrom.value[1] : null
  }
})

// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data

  getData()
}

const handlCheck = async (row: any,status: any)  => {
  //调用查询合同详细信息
  const ids = [row.Id];
  let data={
    "Ids": ids,  //单据id
    "Type":"YKP",  //类型 HTLR 合同录入 TDYS 通电验收  FHYS 发货验收  JSD 结算单  SKJH 收款计划 SKD 收款单 YKP 预收款发票
    "State":status,
  }
  await ApproveDocument(data);
  ElMessage.success("审核成功")
  await getData()
}

//页面加载查询后端数据
onMounted(() => {
  getData()
  initRoleList()
  getUserList()
  getContractData()
})

watch(
()=>cubasdoc.contractList,
val=>{
  getContractData()
},
{deep:true}

)

// 获取数据
const getContractData = async () => {
  contractList.value = cubasdoc.contractList.filter((its) => {
    if(its.IsYKP!==undefined){
      return (its.IsYKP==='是')
    }
  })
  console.log("YKP",contractList.value)
}

// 获取数据
const getData = async () => {
  state.loading = true
  let data = await selcetDataList(getQueryData.value)
  state.table.data = data
  state.loading = false
}

//过滤单位
const cnvbasdocMethod = query => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter(its => {
        return (
          its.cCusCode.toLowerCase().includes(query.toLowerCase()) ||
          its.ccusabbname.toLowerCase().includes(query.toLowerCase())
        )
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

function updateContarctInfo (contractInfo) {
  //查询过滤合同信息
  if (contractInfo){
    console.log(contractInfo,"选择合同信息")
    state.formData.ProjectName = contractInfo?.ProjectName
    state.formData.ContractNum = contractInfo?.ContractNum
    state.formData.JobNum = contractInfo?.JobNum
    state.formData.CustName = contractInfo?.CustName
    state.formData.CustAdd = contractInfo?.CustAdd
    state.formData.Rate = contractInfo?.Rate
    state.formData.ContractId = contractInfo?.Rate

    state.formData.BankCode =contractInfo?.BankCode
    state.formData.BankAccount =contractInfo?.BankAccount
    state.formData.Tax = contractInfo?.Tax

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)

    //查询业务员
    console.log(contractInfo.SaleCode,"收到你说的")
    if(contractInfo.SaleCode){
      findSalesMan(contractInfo.SaleCode)
    }
  }
}


const findSalesMan = async (code)=>{
  let data = await  GetSalesMan({Code:code})
  state.formData.Salesman = data.Data

  //过滤客户
  let useroptions = state.userList.filter(its =>
      its.cPsn_Num.toLowerCase().includes(state.formData.Salesman.toLowerCase())
  )
  console.log(state.userList,useroptions,code)
  if (useroptions.length > 0) {
    //赋值
    state.formData.DeptName = useroptions[0].cDepName
    state.formData.DeptCode = useroptions[0].cDept_num
    state.formData.SalesmanName = useroptions[0].cPsn_Name
  }
}



//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })


  if (Data?.SubList) {
    //赋值合同明细
    state.editTable.data = Data.SubList
  }
}

//打开新增窗口
function addHandle() {
  state.formData = {
    Ddate: parseTime(new Date(), '{y}-{m}-{d}'),
  }
  state.dialogSelectEnt = true
  state.isEdit = true
  state.title='新增预开票收款'
}

const selectTableFP= ref(null)
//关闭弹窗
function closeDialog() {
  selectTableFP.value?.clear()
  state.dialogSelectEnt = false
  state.detail.dialogSelectEnt = false
  reset()
}

// 添加数据条数
const num = ref(1)
const singleEdit: any = ref(null)
// 添加数据
const add = () => {
  if (num.value > 0) {
    for (let i = 0; i < num.value; i++) {
      state.editTable.data.push({})
    }
  }
}

// 重置表单
const reset = () => {
  state.coseData= []
  state.defaultSelectVal=[]
  state.editTable.data=[]
  singleEdit.value?.resetFields()

  state.formData = {}
  state.clumTable.data = []
}

//下拉表格选择数据
const selectionChange = e => {
  state.coseData = e

}

//下拉表格选择数据
const selecUpdateChange = e => {
  state.selectedRow = e
}

//选择标的
const addToTable = () => {
  if (state.coseData.length <= 0) {
    ElNotification.error({
      title: '提示',
      message: '请选择标的',
      offset: 200,
    })
    return
  }


  state.coseData.forEach(item => {
    //相同数据不能添加
    if (state.clumTable.data.find(item1 => item1.Id === item.Id || item1.ConSubId === item.Id)) {
      ElNotification.error({
        title: '提示',
        message: item.CinvName + '已存在，请勿重复添加',
        offset: 200,
      })
      return
    }

     let rate = (state.formData.Rate /100) + 1
    let Qty = {
      ...item,
      Qty:item.Quantity,
      ConSubId: item.Id,
      UnPrice:(Number(item.Price || 0) / rate).toFixed(5),
      UnAmount:((item.Amount || 0 ) * rate).toFixed(2),
      Rate: state.formData.Rate,
    }
    state.clumTable.data.push(Qty)
  })
}

//校验表单需要定义ref
let formRef = ref({})
// 提交表单
function submitForm() {
  //校验提交表单
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (state.clumTable.data.length <= 0) {
        ElNotification.error({
          title: '提示',
          message: '请选择标的',
          offset: 200,
        })
        return
      }

      let data = {
        Main: {
          ...state.formData,
          State: '0',

        },
        SubList: state.clumTable.data
      }

      let { Code } = await SaveFHYS(data)
      if (Code === 'OK') {
        ElNotification.success({
          title: '提示',
          message: '保存成功',
          offset: 200,
        })
        closeDialog()
        await getData()
      }
    }
  })
}

//删除表单
function deleteHandles(row) {
  const ids = row.Id ? [row.Id] : state.ids


  ElMessageBox.confirm('请仔细核对数据，删除后无法恢复！', '审核提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      DelJHYS({ Ids: ids })
      ElNotification.success({
        title: '提示',
        message: '删除成功',
        offset: 200,
      })
      setTimeout(() => {
        getData()
        // 这里执行下一步操作
      }, 200); // 等待3秒
    })
    .catch(() => {})
}

function changeSalesman(e) {
  //过滤客户
  let useroptions = state.userList.filter(its =>
    its.cPsn_Num.toLowerCase().includes(e.toLowerCase())
  )
  if (useroptions) {
    //赋值
    state.formData.DeptName = useroptions[0].cDepName
    state.formData.DeptCode = useroptions[0].cDept_num
    state.formData.SalesmanName = useroptions[0].cPsn_Name
  }
}

//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

// 数量change事件
const numChange = (val, prop, scope) => {

  let rate = (state.clumTable.data[scope.$index].Rate /100) + 1

  state.clumTable.data[scope.$index].Amount= (Number(state.clumTable.data[scope.$index].Qty || 0) * Number(state.clumTable.data[scope.$index].Price || 0)).toFixed(2)//含税金额
  state.clumTable.data[scope.$index].UnPrice=(Number(state.clumTable.data[scope.$index].Price || 0) / rate).toFixed(5)//不含税单价=含税单价 / 1.13

  state.clumTable.data[scope.$index].UnAmount=((state.clumTable.data[scope.$index].Amount || 0 ) * rate).toFixed(2)//不含税金额 = 含税金额 * 1.13
  state.clumTable.data[scope.$index].Tax=( (state.clumTable.data[scope.$index].Amount || 0) - ((state.clumTable.data[scope.$index].Amount || 0) / rate)).toFixed(2)//税额
  state.clumTable.data[scope.$index].JSAmount=state.clumTable.data[scope.$index].Amount
}

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '预收款开票' })
  state.roleList = res.items
}
</script>

<style lang="scss" scoped>
.single_edit_demo {
  .add_data {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
  }
}
</style>
